from favicon.models import Favicon, FaviconURI, Client, Access, CountStat, DateCountStat
from datetime import datetime

def inc_total_favicons():
  total_favicons = CountStat.get_or_insert("total_favicons")
  total_favicons.count += 1
  total_favicons.put()

def get_total_favicons():
  total_favicons = CountStat.get_by_key_name("total_favicons")
  return total_favicons.count

def inc_total_accesses():
  total_accesses = CountStat.get_or_insert("total_accesses")
  total_accesses.count += 1
  total_accesses.put()

def get_total_accesses():
  total_accesses = CountStat.get_by_key_name("total_accesses")
  return total_accesses.count

def inc_today_accesses():
  today = datetime.today()
  total_accesses_today = DateCountStat.get_or_insert("accesses_%04d%02d%02d" % (today.year, today.month, today.day), date=today)
  total_accesses_today.type = "accesses"
  total_accesses_today.count += 1
  total_accesses_today.put()

def get_today_accesses():
  today = datetime.today()
  total_accesses_today = DateCountStat.get_by_key_name("accesses_%04d%02d%02d" % (today.year, today.month, today.day))
  return total_accesses_today.count

def inc_today_favicons():
  today = datetime.today()
  total_favicons_today = DateCountStat.get_or_insert("favicons_%04d%02d%02d" % (today.year, today.month, today.day), date=today)
  total_favicons_today.type = "favicons"
  total_favicons_today.count += 1
  total_favicons_today.put()

def get_today_favicons():
  today = datetime.today()
  total_favicons_today = DateCountStat.get_by_key_name("favicons_%04d%02d%02d" % (today.year, today.month, today.day))
  return total_favicons_today.count

def get_num_favicons(num):
  counts = DateCountStat.all().filter('type =', 'favicons').order('-date').fetch(num)
  return [ str(cnt.count) for cnt in counts ]

def inc_today_updates():
  today = datetime.today()
  total_updates_today = DateCountStat.get_or_insert("updates_%04d%02d%02d" % (today.year, today.month, today.day), date=today)
  total_updates_today.type = "updates"
  total_updates_today.count += 1
  total_updates_today.put()

def get_today_updates():
  today = datetime.today()
  total_updates_today = DateCountStat.get_by_key_name("updates_%04d%02d%02d" % (today.year, today.month, today.day))
  return total_updates_today.count

# favicon fetch methods
def most_recently_accessed(num):
  return Access.all().order('-created_at').fetch(num)

def most_accessed(num):
  return Favicon.all().filter('active = ', True).order('-accesses').fetch(num)

def most_recently_added(num):
  return Favicon.all().filter('active = ', True).order('-created_at').fetch(num)

def datetime_url(dt):
  return "/api/%04d/%02d/%02d/%02d/%02d/%02d/%d/" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)
  

# hack to make key_name begin with a letter
def md5_key(md5):
  return 'a' + md5
